package com.zhangpf.boot.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 描述：时间工具类
 */
public class DateUtils {
    private static final Logger logger = LoggerFactory.getLogger(DateUtils.class);

    public static final String yyyyMMdd = "yyyyMMdd";

    public static final String yyyy_MM_dd = "yyyy-MM-dd";

    public static final String STANDARD_PATTERN ="yyyy-MM-dd HH:mm:ss";

    public static boolean isValidDate(String str,String pattern) {
        try {
            LocalDate.parse(str, DateTimeFormatter.ofPattern(pattern));
            return true;
        }catch (Exception e){
            logger.error("待转换时间：{},不是此：{}格式的正确时间，强转异常：{}",str,pattern,e);
            return false;
        }
    }

    public static boolean isLegalDate (String beginDate,String endDate,String pattern) {
        try{
            LocalDate beginDateTime = LocalDate.parse(beginDate, DateTimeFormatter.ofPattern(pattern));
            LocalDate endDateTime = LocalDate.parse(endDate, DateTimeFormatter.ofPattern(pattern));
            int i = endDateTime.compareTo(beginDateTime);
            return i>=0;
        }catch (Exception e){
            logger.error("开始时间：{}晚于结束时间：{}，时间错误！",beginDate,endDate,e);
            return false;
        }
    }

    public static String parseDateToString(LocalDateTime dateTime,String pattern){
        return dateTime.format(DateTimeFormatter.ofPattern(pattern));
    }


    /***
     * <p>Description: 将时间字符串转换为相同时间格式的时间</p>
     * @param dateTime 时间字符串
     * @param pattern 格式
     * @return java.time.LocalDateTime
     * @author zhangjunping
     * @date 2019/7/26 10:20
     */
    public static LocalDateTime parseStringToDateTime(String dateTime,String pattern){
        Assert.notNull(dateTime,"parseStringToDateTime dateTime is null");
        Assert.notNull(pattern,"parseStringToDateTime pattern is null");
        return LocalDateTime.parse(dateTime,DateTimeFormatter.ofPattern(pattern));
    }

    /***
     * <p>Description: 给定时间是否在开始时间及结束时间之间</p>
     * @param dateTime 给定时间
     * @param begin 开始时间
     * @param end 结束时间
     * @return boolean
     * @author zhangjunping
     * @date 2019/7/26 10:07
     */
    public static boolean betweenBeginAndEnd(LocalDateTime dateTime,LocalDateTime begin,LocalDateTime end){
        return dateTime.isBefore(end) && dateTime.isAfter(begin);
    }



}
